<template>
	<view class="val-code" :class="{'opacity-font': countTime.step !== 1}" @tap="sendCode">
		<text v-if="countTime.step === 1" :style="'color:'+fontColor">{{i18n.code}}</text>
		<image v-else-if="countTime.step === 2" class="loading" src="/static/img/newUser/loading.png" mode=""></image>
		<text v-else-if="countTime.step === 3" :style="'color:'+fontColor">{{countTime.currentTime}}s</text>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				countTime: {
					time: 60,
					currentTime: 0,
					step: 1,
					lock: false,
					setIntervalFun: null
				}
			}
		},
		props: {
			step: {
				// 1 获取验证码 2 loading 3 倒计时
				type: Number
			},
			fontColor: {
			  type: String,
			  default: ''
			},
		},
		watch: {
			step(val) {
				this.countTime.step = val;
				if (val === 3) {
					this.startCountDown();
				} else if (val === 1) {
					clearInterval(this.countTime.setIntervalFun);
					this.countTime.lock = false;
				}
			}
		},
		computed: {
		    i18n() {
		    	return this.$t('components');
		    }
		},
		methods: {
			sendCode() {
				if (this.countTime.lock) {
					return false;
				}
				this.$emit('on-send');
			},
			startCountDown() {
				this.countTime.lock = true;
				this.countTime.currentTime = this.countTime.time;
				let _this = this;
				this.countTime.setIntervalFun = setInterval(function() {
					if (_this.countTime.currentTime > 0) {
						_this.countTime.currentTime--;
					} else {
						clearInterval(_this.countTime.setIntervalFun);
						_this.countTime.lock = false;
						_this.countTime.step = 1;
					}
				}, 1000);
			}
		}
	}
</script>

<style lang="less" scoped>
	.val-code {
		min-width: 160upx;
		text-align: center;
		font-size: 28upx;
		color: var(--theme-color);
		&:hover {
			color: var(--theme-color);
		}

		.loading {
			display: inline-block;
			width: 32upx;
			height: 32upx;
			animation: rotate 1s linear infinite;
			transform-origin: center center;
		}

		&.opacity-font {
			cursor: not-allowed;
			color: #999;

			&:hover {
				color: #999;
			}
		}
	}

	@-webkit-keyframes rotate {
		to {
			-webkit-transform: rotate(1turn);
			transform: rotate(1turn)
		}
	}

	@keyframes rotate {
		to {
			-webkit-transform: rotate(1turn);
			transform: rotate(1turn)
		}
	}
</style>
